package domino;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.datatransfer.*;
import java.awt.dnd.*;

class FichaBoton extends JButton implements Transferable, DragSourceListener, DragGestureListener {

    private Ficha ficha;
    private JPanel panel = null;
    private DragSource source;
    private TransferHandler t;
    private boolean utilizada;
    private ConectorJuego conector;

    public Ficha getFicha() {
        return ficha;
    }

    public void setFicha(Ficha value) {
        ficha = value;
        actualizar();
    }

    private void actualizar() {
        setText(ficha.toString());
    }

    public JPanel getPanel() {
        return panel;
    }

    public void setPanel(JPanel value) {
        panel = value;
    }
    
    public ConectorJuego getConector() { return conector; }
    public void setConector(ConectorJuego value) { conector = value; }    
    
    public boolean getUtilizada(){ return utilizada; }
    public void setUtilizada(boolean value) { utilizada = value;}

    public FichaBoton(String f) {
        this(new Ficha(f));
    }

    public FichaBoton(Ficha f) {
        super(f.toString());
        this.setFicha(f);
        setSize(80, 40);

        t = new TransferHandler() {

            public Transferable createTransferable(JComponent c) {
                return new FichaBoton(getText());
            }
        };
        setTransferHandler(t);
        source = new DragSource();
        source.createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_COPY, this);

        addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                FichaBoton b = (FichaBoton) e.getSource();
                b.voltear();
            }
        });
    }

    public void voltear() {
        if(!this.utilizada){
            this.ficha.voltear();
            actualizar();
        }
    }

    public DataFlavor[] getTransferDataFlavors() {
        return new DataFlavor[]{new DataFlavor(FichaBoton.class, "FichaBoton")};
    }

    public boolean isDataFlavorSupported(DataFlavor flavor) {
        return true;
    }

    public Object getTransferData(DataFlavor flavor) {
        return this;
    }

    public void dragEnter(DragSourceDragEvent dsde) {
    }

    public void dragOver(DragSourceDragEvent dsde) {
    }

    public void dropActionChanged(DragSourceDragEvent dsde) {
    }

    public void dragExit(DragSourceEvent dse) {
    }

    public void dragDropEnd(DragSourceDropEvent dsde) {
        repaint();
        if (!this.getUtilizada() && dsde.getDropSuccess() && panel != null) {
            this.setUtilizada(true);
            panel.remove(this);
            panel.repaint();
        }
    }

    public void dragGestureRecognized(DragGestureEvent dge) {
        if(!this.getUtilizada()){
            source.startDrag(dge, DragSource.DefaultMoveDrop, this, this);
        }
    }
}